import pyaudio
import dashscope
from dashscope.audio.asr import *
from PyQt5.QtCore import QThread,pyqtSignal
# 若没有将API Key配置到环境变量中，需将your-api-key替换为自己的API Key
dashscope.api_key = "sk-eb8796c78a584ae4a511c75459d13c0c"

mic = None
stream = None

class Callback(TranslationRecognizerCallback):
    def __init__(self,window):
        self.window=window;
        self.sentence_id=0;
        self.all_text = "";
        self.last_text = "";

    def on_open(self) -> None:
        global mic
        global stream
        print("录音中...start.")
        mic = pyaudio.PyAudio()
        stream = mic.open(
            format=pyaudio.paInt16, channels=1, rate=16000, input=True
        )
        self.sentence_id = 0;
        self.all_text = "";
        self.last_text= "";


    def on_close(self) -> None:
        global mic
        global stream
        print("录音结束... close.")
        stream.stop_stream()
        stream.close()
        mic.terminate()
        stream = None
        mic = None

    def on_event(
        self,
        request_id,
        transcription_result: TranscriptionResult,
        translation_result: TranslationResult,
        usage,
    ) -> None:
        if transcription_result is not None:
            print("sentence id: ", transcription_result.sentence_id)
            print("transcription: ", transcription_result.text)
            if transcription_result.stash is not None:
                print("transcription stash: ", transcription_result.stash.text)
            if transcription_result.sentence_id==self.sentence_id:
                self.last_text=transcription_result.text;
                self.window.evaluate_js("setMsg(\"" + (self.all_text+self.last_text) + "\")")
            elif transcription_result.sentence_id>self.sentence_id:
                self.sentence_id+=1;
                self.all_text = self.all_text+self.last_text;


class SpeakToText(QThread):
    signal_result = pyqtSignal(str)

    def __init__(self,window):
        super().__init__()  # 调用父类的构造方法
        self._stop_flag = False  # 停止标志
        callback = Callback(window)
        self.translator = TranslationRecognizerRealtime(
            model="gummy-realtime-v1",
            format="pcm",
            sample_rate=16000,
            transcription_enabled=True,
            translation_enabled=True,
            translation_target_languages=["ch"],
            callback=callback,
        )
    def run(self):
        try:
            self.translator.start()
        except Exception as e:
            print(f"Caught exception: {e}")
        print("listening...")
        self._stop_flag=False;
        while not self._stop_flag:
            if stream:
                data = stream.read(3200, exception_on_overflow=False)
                self.translator.send_audio_frame(data)
            else:
                break
        print("translator.stop()...")

        self.translator.stop()

    def stop(self):
        self._stop_flag = True
        self.wait()  # 等待线程完成
#
# if __name__ == '__main__':
#     SpeakToText().startListen()